package com.js.statemachine.config.uml;

import com.js.statemachine.common.EventConst;
import com.js.statemachine.config.StateMachineEventListener;
import com.js.statemachine.service.uml.MpStateMachineBizInter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.statemachine.action.Action;
import org.springframework.statemachine.config.EnableStateMachineFactory;
import org.springframework.statemachine.config.StateMachineConfigurerAdapter;
import org.springframework.statemachine.config.builders.StateMachineConfigurationConfigurer;
import org.springframework.statemachine.config.builders.StateMachineModelConfigurer;
import org.springframework.statemachine.config.model.StateMachineModelFactory;
import org.springframework.statemachine.uml.UmlStateMachineModelFactory;

import javax.annotation.Resource;

/**
 * @author ：js
 * @date ：Created in 2021-02-20 13:56
 * @description: 表计状态机配置
 * @version:1.0
 */
@Configuration
@Slf4j
@EnableStateMachineFactory(name = "mpStateMachineFactory")
@Scope("prototype")
public class MpStateMachineConfig extends StateMachineConfigurerAdapter<String, String> {

    @Resource
    private StateMachineEventListener stateMachineEventListener;

    @Autowired
    private MpStateMachineBizInter mpStateMachineBizInter;

    public static final String mpStateMachineId = "mp";

    @Override
    public void configure(StateMachineConfigurationConfigurer<String, String> config)
            throws Exception {
        config
                .withConfiguration().listener(stateMachineEventListener)
                .autoStartup(true).machineId(mpStateMachineId);
    }

    @Override
    public void configure(StateMachineModelConfigurer<String, String> model) throws Exception {
        model
                .withModel()
                .factory(mpFactory());
    }

    @Bean
    public StateMachineModelFactory<String, String> mpFactory() {
        return new UmlStateMachineModelFactory("classpath:MeasurePoint_State_Machine.uml");
    }

    /**
     * 开通计量点业务
     *
     * @return
     */
    @Bean
    public Action<String, String> openBiz() {
        return context -> {
            boolean flag;
            try {
                flag = mpStateMachineBizInter.open(context.getMessage());
                if (flag) {
                    context.getStateMachine().sendEvent(EventConst.OPEN_COMPLETED);
                } else {
                    context.getStateMachine().sendEvent(EventConst.OPEN_FAIL);
                }
            } catch (Exception e) {
                log.error("出现异常");
                context.getStateMachine().sendEvent(EventConst.OPEN_FAIL);
            }
        };
    }


}


